package com.cskaoyan.service.wx.llk;

import com.cskaoyan.bean.wx.llk.CollectListBean;
import com.cskaoyan.bean.wx.llk.WxCollect;
import com.cskaoyan.bean.wx.llk.WxCollectExample;
import com.cskaoyan.bean.wx.llk.WxCollectVO;
import com.cskaoyan.mapper.wx.llk.WxCollectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @date :  2021/1/13 15:09
 */
@Service
public class WxCollectServiceImpl implements WxCollectService {
    @Autowired
    WxCollectMapper wxCollectMapper;

    @Override
    public WxCollectVO<CollectListBean> queryList(Integer type, Integer page, Integer size, Integer userId) {
        Page<Object> pages = PageHelper.startPage(page, size);

        List<CollectListBean> collectList = wxCollectMapper.selectCollectList(type,userId);
        int total = pages.getPageSize();
        int totalPages = (total / size) + 1;

        return WxCollectVO.data(collectList,totalPages);
    }

    @Override
    public Map<String, String> addOrDeleteCollect(Map<String, Integer> map, Integer userId) {

        Map<String, String> resultMap = new HashMap<>();
        //添加前 先判断是否收藏过  是的话取消收藏 不是则添加
        WxCollectExample wxCollectExample = new WxCollectExample();
        WxCollectExample.Criteria criteria = wxCollectExample.createCriteria();
        criteria.andUserIdEqualTo(userId)
                .andValueIdEqualTo(map.get("valueId"))
                .andDeletedEqualTo(false);
        List<WxCollect> wxCollects = wxCollectMapper.selectByExample(wxCollectExample);

        //如果查询结果为0 代表表中没有数据 那执行添加数据
        if (wxCollects.size() == 0){
            resultMap.put("type","add");
            WxCollect wxCollect = new WxCollect(null, userId, map.get("valueId"), map.get("type").byteValue(),
                    new Date(), new Date(), false);
            wxCollectMapper.insertSelective(wxCollect);
            return resultMap;
        }

        //查询结果不为0 ，表中有数据 删除该收藏
        WxCollect wxCollect = new WxCollect();
        wxCollect.setDeleted(true);
        wxCollect.setUpdateTime(new Date());
        wxCollectMapper.updateByExampleSelective(wxCollect,wxCollectExample);
        resultMap.put("type","delete");

        return resultMap;
    }
}
